<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/21
 * Time: 9:53
 * 统计
 */
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Count extends Api {
	protected $noNeedRight = '*';
//	protected $noNeedLogin = '*';
	
	public function index(){
		$date = input('post.date');
		if($date) {
			$bTime = strtotime(date('Y-m-01 00:00:00',strtotime($date)));
			$time = strtotime('+1 months', $bTime);
		} else {
			//开始时间
			$bTime = strtotime(date('Y-m-01 00:00:00'));
			//结束时间
			$time = time();
		}
		
		//统计用户
		$userId = input('post.user_id', $this->auth->id, 'intval');
		!$userId && $userId = $this->auth->id;
		$where = [
			'f.user_id' => $userId,
			'f.date' => [
				['egt', $bTime],
				['lt', $time]
			]
		];
		
		
		$operationType = input('post.operation_type', '', 'intval');
		$operationType && $where['f.operation_type'] = $operationType;
		
		$accountId = input('post.account_id', '', 'intval');
		$accountId && $where['account_id'] = $accountId;
		
		$rows = Db::name('funds')->alias('f')
			->join('fundsType t', 'f.funds_type_id = t.id', 'left')
			->where($where)
			->field('f.id, f.user_id, f.account_id, f.operation_type, f.funds_type_id, f.amount, from_unixtime(f.date, \'%c.%e\') as date, t.name as type_name')
			->order(['f.date' => 'asc'])
			->select();
		
		$returnData = [
			'income' => [],
			'count' => [],
			'consumption' => []
		];
		if($rows) {
			foreach ($rows as $row) {
				$row['amount']  = floatval($row['amount']);
				if(!isset($returnData['count'][$row['date']])) {
					$returnData['count'][$row['date']] = [
						'date' => $row['date'],
						'inc' => 0,
						'des' => 0
					];
				}
				
				
				
				if($row['operation_type'] == \app\common\model\Funds::OPERATION_TYPE_PUSH) {
					$returnData['count'][$row['date']]['inc'] += $row['amount'];
					
					if(!isset($returnData['income'][$row['funds_type_id']])) {
						$returnData['income'][$row['funds_type_id']] = [
							'name' => $row['type_name'],
							'amount' => 0
						];
					}
					
					$returnData['income'][$row['funds_type_id']]['amount'] += $row['amount'];
				} else {
					$returnData['count'][$row['date']]['des'] += $row['amount'];
					
					if(!isset($returnData['consumption'][$row['funds_type_id']])) {
						$returnData['consumption'][$row['funds_type_id']] = [
							'name' => $row['type_name'],
							'amount' => 0
						];
					}
					
					$returnData['consumption'][$row['funds_type_id']]['amount'] += $row['amount'];
				}
			}
			
			$returnData['count'] = array_values($returnData['count']);
			$returnData['income'] = array_values($returnData['income']);
			$returnData['consumption'] = array_values($returnData['consumption']);
		}
		
		$this->success('查询成功'.Db::name('funds')->getLastSql(), $returnData);
	}
}